package com.ghsc.ghxc.jsb.ui.message.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityChatGroupListBinding
import com.ghsc.ghxc.jsb.ui.message.bean.GroupDataResultBeans
import com.ghsc.ghxc.jsb.utils.StringUtil
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message.activity
 * 类名：ChatTeamListActivity
 * 创建时间：2024/5/9 14:17
 * 创建人 @author： xiaolin
 * 描述 ：Todo...群聊成员
 */
class ChatTeamListActivity  : BaseVMActivity<ChatViewModel, ActivityChatGroupListBinding>() {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_chat_group_list
    }

    override fun attachVMClass(): Class<ChatViewModel>? {
        return ChatViewModel::class.java
    }

    private val mAdapter: SearchChatAdapter by lazy { SearchChatAdapter(sign) }
    var mList = arrayListOf<GroupDataResultBeans>()
    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    var bundle : Bundle?=null
    var targetId:String?=""
    var sign :Int =0

    var keyword =""

    @SuppressLint("SetTextI18n")
    override fun initView() {
        bundle=intent.extras
        targetId=bundle!!.getString("targetId","")
        sign=bundle!!.getInt("sign",0)
        binding.run {
            topLeftView.setOnClickListener {
                finish()
            }
            topTitle.text = "群聊成员"
            if (sign==1){
                tvBtnCheck.visibility= View.VISIBLE
                tvBtnCheck.text="移除(0)"
            }else tvBtnCheck.visibility= View.GONE
            llSearch.visibility= View.VISIBLE
        }
        binding.rvList.layoutManager = LinearLayoutManager(this)
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            var  bundle = Bundle()
            bundle.putString("gid",targetId)
            bundle.putString("userIdTa",mAdapter.getItem(position).uid)
            startActivity(ChatSetSingleActivity().javaClass,bundle)
        }
        mAdapter.addChildClickViewIds(R.id.imgCheck)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            //item里面某个按钮事件
            when(view.id){
                R.id.imgCheck ->{
                    mAdapter.data[position].isCheck= !mAdapter.data[position].isCheck
                    mAdapter.notifyItemChanged(position)
                    binding.tvBtnCheck.text="移除("+setCheckNum().size.toString()+")"
                }
            }
        }
        initRefreshLayout()
        pageNo = 1
        getListData()

    }

    override fun initClickListener() {
        super.initClickListener()
        binding.run {
            tvBtnNext.setOnClickListener {
                if (TextUtils.isEmpty(binding.etSearch.text)){
                    showToast("请输入昵称")
                }else{
                    keyword=binding.etSearch.text.toString()
                    pageNo = 1
                    getListData()
                }
            }
            etSearch.isFocusable = true
            etSearch.isFocusableInTouchMode = true
            etSearch.requestFocus()
            etSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener {
                override fun onEditorAction(
                    v: TextView,
                    actionId: Int,
                    event: KeyEvent?
                ): Boolean {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        // 先隐藏键盘
                        hideKeyboard(v)
                        keyword = binding.etSearch.text.toString().trim()
                        if (!TextUtils.isEmpty(keyword)) {
                            binding.etSearch.clearFocus()
                            hideKeyboard(binding.etSearch)
                            pageNo = 1
                            getListData()
                        }else{
                            keyword=""
                            pageNo = 1
                            getListData()
                        }
                        return true
                    }
                    return false
                }
            })
            etSearch.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    if(TextUtils.isEmpty(p0.toString().trim())){
                        keyword=""
                        pageNo = 1
                        getListData()
                    }
                }

            })

        }
    }
    /** 选择好的id **/
    fun setCheckNum():MutableList<String>{
        var mList = arrayListOf<String>()
        for (i in mAdapter.data.indices){
            if (mAdapter.data[i].isCheck)
                mList.add(mAdapter.data[i].uid)
        }
        return mList

    }
    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }
            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }
    private fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["gid"] = targetId!!
        map["pindex"] = pageNo
        map["psize"] = pageSize
        map["keyword"] =keyword
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGroupInfoListMethod(it1) }
    }
    override fun initData() {
        super.initData()
        binding.tvBtnCheck.setSingleClickListener {
            var counts=setCheckNum()
            if (counts.size>0){
                var str= StringUtil.convertListToString(counts)
                val map: HashMap<String, Any> = HashMap()
                map["gid"] = targetId!!
                map["userids"] = str!!
                map["ptype"]= 1
                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGroupJoinMethod(it1) }
            }else showToast("请选择您要移除群到好友...")
        }
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@ChatTeamListActivity) {
                binding.refreshLayout.finishRefresh()
                showToast(it)
            }
            againLoginMsg.observe(this@ChatTeamListActivity) {
                binding.refreshLayout.finishRefresh()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onGroupJoinData.observe(this@ChatTeamListActivity){
                showToast("移除成功")
                finish()
            }

            onGroupInfoListData.observe(this@ChatTeamListActivity){
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    mAdapter.replaceData( it.data.list)
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }

            }


        }
    }

    inner class SearchChatAdapter(sign:Int)  : BaseQuickAdapter<GroupDataResultBeans, BaseViewHolder>(
        R.layout.friends_item) {

        var sign:Int=0
        init {
            this.sign=sign
        }
        override fun convert(helper: BaseViewHolder, item: GroupDataResultBeans) {
            GlideUtil.ImageHeadLoad(this.context,item.headimg,helper.getView(R.id.userImgUrl))
            helper.setText(R.id.tvName,item.nickname)
                .setGone(R.id.tvBtnNext, true)
                .setGone(R.id.imgCheck,false)
            if(sign==0){
                helper.setGone(R.id.imgCheck,true)
            }else
                helper.setGone(R.id.imgCheck,false)
            if (item.isCheck)
                helper.setImageResource(R.id.imgCheck,R.mipmap.icon_cb_default_checked)
            else helper.setImageResource(R.id.imgCheck,R.mipmap.icon_cb_default_not_checked)





        }
    }


}
